import videoAPI from './videoAPI';

const videoUploader = async file => {
  const stsRes = await videoAPI.getSTS();
  return new Promise((resolve, reject) => {
    if (stsRes.data) {
      const config = { ...stsRes.data };
      const uploader = new window.AliyunUpload.Vod({
        // STS临时账号会过期，过期时触发函数
        onUploadTokenExpired() {
          videoAPI.getSTS().then(c => {
            uploader.resumeUploadWithSTSToken(
              c.tempKeyId,
              c.tempKeySecret,
              c.securityToken,
              c.expiration
            );
          });
        },
        // 开始上传
        onUploadstarted(uploadInfo) {
          uploader.setSTSToken(
            uploadInfo,
            config.tempKeyId,
            config.tempKeySecret,
            config.securityToken
          );
        },
        // 文件上传完成
        onUploadSucceed(uploadInfo) {
          console.log(uploadInfo);
          const { videoId } = uploadInfo;
          const getVideoInfo = id => {
            videoAPI
              .getVideoInfo(id)
              .then(({ data, status, message }) => {
                if (status === 'success') {
                  /* 要以必要元素为判断依据，在前面的几次返回data为null，有时coverUrl等必要元素可能为null，继续轮训请求即可 */
                  if (!(data && data.coverUrl)) {
                    setTimeout(() => getVideoInfo(id), 2000);
                  } else {
                    resolve(data);
                  }
                } else {
                  reject(message);
                }
              })
              .catch(e => {
                reject(e);
              });
          };
          getVideoInfo(videoId);
        },
        // 文件上传失败
        onUploadFailed() {
          reject();
        }
      });
      uploader.addFile(
        file,
        null,
        null,
        null,
        '{"Vod":{"Title":"im视频消息"}}'
      );
      uploader.startUpload();
    }
  });
};

export default videoUploader;
